package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.common.PageResult;
import cn.itcast.hotel.dto.HotelPageQueryDTO;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.service.HotelService;
import cn.itcast.hotel.vo.HotelVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 酒店服务
 *
 * @author liudo
 * @date 2023/08/15
 */
@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    private static final String HOTEL = "hotel";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult<HotelVO> pageList(HotelPageQueryDTO hotelPageQueryDTO) {
        int from = (hotelPageQueryDTO.getPage() - 1) * hotelPageQueryDTO.getSize();
        SearchRequest searchRequest = new SearchRequest(HOTEL);
        // 如果key为空则不拼接条件
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(hotelPageQueryDTO);
        // 查询 boolQueryBuilder
        searchRequest.source().query(
                QueryBuilders.functionScoreQuery(
                                boolQueryBuilder,
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                                QueryBuilders.termQuery("ad", true),
                                                ScoreFunctionBuilders.weightFactorFunction(10F)
                                        )
                                }
                        )
                        .boostMode(CombineFunction.SUM)
        );
        // 排序
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getLocation())) {
            searchRequest.source().sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(hotelPageQueryDTO.getLocation()))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }
        // 分页
        searchRequest.source()
                .from(from)
                .size(hotelPageQueryDTO.getSize());
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();

            List<HotelVO> hotelVOS = Arrays.stream(hitsHits).map(hit -> {
                // json
                String sourceAsString = hit.getSourceAsString();
                HotelVO hotelVO = JSON.parseObject(sourceAsString, HotelVO.class);
                if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getLocation())) {
                    // 在这里取距离
                    Object[] sortValues = hit.getSortValues();
                    if (sortValues != null && sortValues.length > 0) {
                        Object sortValue = sortValues[0];
                        hotelVO.setDistance(sortValue);
                    }
                }
                return hotelVO;
            }).collect(Collectors.toList());


            PageResult<HotelVO> hotelVOPageResult = new PageResult<>();
            hotelVOPageResult.setTotal(total);
            hotelVOPageResult.setData(hotelVOS);
            return hotelVOPageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, List<String>> filters(HotelPageQueryDTO hotelPageQueryDTO) {
        SearchRequest searchRequest = new SearchRequest(HOTEL);
        String brandAgg = "brandAgg";
        String cityAgg = "cityAgg";
        String starNameAgg = "starNameAgg";
        // 增加过滤条件
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(hotelPageQueryDTO);
        searchRequest.source()
                // 添加条件
                .query(boolQueryBuilder)
                .size(0)
                .aggregation(
                        AggregationBuilders.terms(brandAgg)
                                .field("brand")
                                .size(20)
                )
                .aggregation(
                        AggregationBuilders.terms(cityAgg)
                                .field("city")
                                .size(20)
                )
                .aggregation(
                        AggregationBuilders.terms(starNameAgg)
                                .field("starName")
                                .size(20)
                );
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            // 经过分析得到具体的类型
            ParsedStringTerms aggregationBrand = aggregations.get(brandAgg);
            ParsedStringTerms aggregationCity = aggregations.get(cityAgg);
            ParsedStringTerms aggregationStarName = aggregations.get(starNameAgg);

            List<? extends Terms.Bucket> bucketsBrand = aggregationBrand.getBuckets();
            List<? extends Terms.Bucket> bucketsCity = aggregationCity.getBuckets();
            List<? extends Terms.Bucket> bucketsStarName = aggregationStarName.getBuckets();

            List<String> brandList = bucketsBrand.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());

            List<String> cityList = bucketsCity.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());

            List<String> starNameList = bucketsStarName.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());

            HashMap<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("city", cityList);
            map.put("starName", starNameList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<String> suggestion(String key) {
        SearchRequest searchRequest = new SearchRequest("hotel");
        String suggestionSuggest = "suggestionSuggest";
        searchRequest.source()
                .suggest(
                        new SuggestBuilder()
                                .addSuggestion(
                                        suggestionSuggest,
                                        SuggestBuilders.completionSuggestion("suggestion")
                                                .prefix(key)
                                                .skipDuplicates(true)
                                                .size(10)
                                )
                );

        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            // 这里最好断点分析一下类型
            CompletionSuggestion completionSuggestion = suggest.getSuggestion(suggestionSuggest);
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            return options.stream()
                    .map(option -> option.getText().string())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取bool查询生成器
     *
     * @param hotelPageQueryDTO 酒店页面查询dto
     * @return {@link BoolQueryBuilder}
     */
    private static BoolQueryBuilder getBoolQueryBuilder(HotelPageQueryDTO hotelPageQueryDTO) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getKey())) {
            boolQueryBuilder.must(
                    QueryBuilders.matchQuery("all", hotelPageQueryDTO.getKey())
            );
        } else {
            boolQueryBuilder.must(
                    QueryBuilders.matchAllQuery()
            );
        }
        // 城市
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getCity())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("city", hotelPageQueryDTO.getCity())
                    );
        }
        // 品牌
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getBrand())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("brand", hotelPageQueryDTO.getBrand())
                    );
        }
        // 星级
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getStarName())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("starName", hotelPageQueryDTO.getStarName())
                    );
        }
        // 价格
        if (Objects.nonNull(hotelPageQueryDTO.getMinPrice()) &&
                Objects.nonNull(hotelPageQueryDTO.getMaxPrice())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.rangeQuery("price")
                                    .gte(hotelPageQueryDTO.getMinPrice())
                                    .lte(hotelPageQueryDTO.getMaxPrice())
                    );
        }
        return boolQueryBuilder;
    }
}
